﻿//*********************************************************

//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Microsoft Public License.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

//*********************************************************

///<summary>
///Class Name: ODataTestGen.OData.EdmxParser
///This class accepts either a service uri or a local edmx file, parses the metadata in xml format and store it in EdmItemCollection form.
///Exceptions: Runtime exceptions might be thrown out if the metadata is not a valid xml file. All the exceptions are caught by the upper level and displayed in form of MessageBox
///</summary>

namespace ODataTestGen.OData
{
    using System;
    using System.Data.Metadata.Edm;
    using System.Linq;
    using System.Xml;
    using System.Xml.Linq;

    public class EdmxParser
    {
        public EdmItemCollection Metadata { get; set; }

        public XElement ParseEdmxFromFile(string fileName)
        {
            XElement edmx = XElement.Load(fileName);

            this.ParseEdmxDocument(edmx);
            return edmx;
        }

        public XElement ParseEdmxFromService(string serviceUri)
        {
            if (!serviceUri.EndsWith("/", StringComparison.Ordinal))
            {
                serviceUri += "/";
            }
            string metadataUri = serviceUri + "$metadata";
            XElement edmx = XElement.Load(metadataUri);
            this.ParseEdmxDocument(edmx);

            return edmx;
        }

        ///<summary>
        ///Function Name: ParseEdmxDocument
        ///This function accepts a XElement that stores the entire metadata, parses the metadata in xml format and store it in EdmItemCollection form.
        ///A temporary edmx file is saved under the TextTemplating folder. This saves efforts when generating the tests.
        ///Exceptions: Runtime exceptions might be thrown out if schema's namespace doesn't pass the verification of creating new EdmItemCollection instance.
        ///</summary>

        private void ParseEdmxDocument(XElement edmx) 
        {
            XElement dataServicesElement = edmx.Element(ODataConstants.EdmxNamespace + "DataServices");
            XElement[] schemas = dataServicesElement.Elements().Where(c => c.Name.LocalName == "Schema").ToArray();
            XmlReader[] readers = schemas.Select(c => c.CreateReader()).ToArray();
            this.Metadata = new EdmItemCollection(readers);
        }
    }
}